import { ref, reactive } from 'vue'
import API_CONFIG from '../config/api.js'
import { queuedFetch } from '../utils/queuedRequest.js'

export function useIndicatorAPI() {
  const isLoading = ref(false)
  const loadingProgress = ref(0)
  const error = ref(null)

  // 获取单个指标数据 - 基于原始代码逻辑
  const getIndicatorData = async (indicatorName) => {
    return new Promise((resolve, reject) => {
      try {
        const name = typeof indicatorName === 'object' ? indicatorName.name : indicatorName
        const extraWhere = typeof indicatorName === 'object' && indicatorName.where ? ` and ${indicatorName.where}` : ''
        console.debug('[IndicatorAPI] 开始获取指标数据:', name, extraWhere ? `(附加条件: ${extraWhere})` : '')
        
        // 准备POST数据 - 使用配置文件中的设置
        var postData = new URLSearchParams()
        const dbConfig = API_CONFIG.getDatabaseConfig()
        const requestParams = dbConfig.API.REQUEST_PARAMS
        
        postData.append('action', requestParams.action)
        postData.append('jdbcName', requestParams.jdbcName)
        postData.append('enc', requestParams.enc)
        
        // SQL查询 - 使用配置文件中的SQL模板
        let sql = API_CONFIG.buildSQL.getIndicatorData(name, null, extraWhere)
        sql = encodeURIComponent(sql)
        // 调试级别打印，必要时再打开
        // console.debug('[IndicatorAPI] 编码后的SQL:', sql)
        sql = btoa(sql)
        // console.debug('[IndicatorAPI] Base64编码的SQL:', sql)
        
        postData.append('sql', sql)
        postData.append('pageIndex', 'undefined')
        postData.append('pageSize', requestParams.pageSize)
        postData.append('isSys', requestParams.isSys)
        postData.append('t', Date.now().toString())
        
        // 创建XMLHttpRequest - 按照原始代码
        var xhr = new XMLHttpRequest()
        
        // 完全按照原始代码构建URL
        const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
        // console.debug('[IndicatorAPI] API请求URL:', apiUrl, 'host:', window.location.host)
        
        xhr.open('POST', apiUrl, true)
        
        // 设置请求头 - 使用配置文件中的设置
        const headers = API_CONFIG.HEADERS
        xhr.setRequestHeader('Content-Type', headers['Content-Type'])
        xhr.setRequestHeader('X-Requested-With', headers['X-Requested-With'])
        xhr.setRequestHeader('Accept', headers['Accept'])
        xhr.setRequestHeader('Accept-Language', headers['Accept-Language'])
        
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              // 成功仅打印简要信息，避免刷屏
              try {
                const preview = JSON.parse(xhr.responseText)
                console.debug('[IndicatorAPI] 请求成功:', name, 'records:', Array.isArray(preview?.datas) ? preview.datas.length : 0)
              } catch (_) {
                console.debug('[IndicatorAPI] 请求成功:', name)
              }
              
              try {
                var jsonResponse = JSON.parse(xhr.responseText)
                resolve(jsonResponse)
              } catch (e) {
                console.error('[IndicatorAPI] JSON解析失败:', e)
                reject(new Error('响应不是有效的JSON格式: ' + xhr.responseText.substring(0, 100)))
              }
            } else {
              console.error('[IndicatorAPI] 请求失败:', xhr.status, xhr.statusText)
              reject(new Error(`请求失败: ${xhr.status} ${xhr.statusText}`))
            }
          }
        }
        
        xhr.onerror = function() {
          console.error('[IndicatorAPI] 网络请求错误')
          reject(new Error('网络请求失败'))
        }
        
        xhr.ontimeout = function() {
          console.error('[IndicatorAPI] 请求超时')
          reject(new Error('请求超时'))
        }
        
        // 设置超时时间
        xhr.timeout = 30000 // 30秒
        
        // 发送请求
        xhr.send(postData)
        
      } catch (err) {
        console.error('[IndicatorAPI] 创建请求时发生错误:', err)
        reject(err)
      }
    })
  }

  // 批量获取指标数据
  const loadKeyIndicators = async (indicatorNames) => {
    isLoading.value = true
    loadingProgress.value = 0
    error.value = null
    
    try {
      const promises = indicatorNames.map(name => getIndicatorData(name))
      const results = []
      
      // 使用Promise.allSettled来处理部分失败的情况
      for (let i = 0; i < promises.length; i++) {
        try {
          const result = await promises[i]
          const displayName = typeof indicatorNames[i] === 'object' ? indicatorNames[i].name : indicatorNames[i]
          results.push({ name: displayName, data: result, success: true })
        } catch (err) {
          const displayName = typeof indicatorNames[i] === 'object' ? indicatorNames[i].name : indicatorNames[i]
          results.push({ name: displayName, error: err, success: false })
        }
        
        loadingProgress.value = Math.round(((i + 1) / promises.length) * 100)
      }
      
      return results
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      isLoading.value = false
    }
  }

  return {
    isLoading,
    loadingProgress,
    error,
    getIndicatorData,
    loadKeyIndicators
  }
}
